<template>
  <div>
     <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>新闻管理</span>
        <el-button v-if="userType=='0'" type="primary" style="float: right;
    padding: 5px 10px;
    position: relative;
    top: -5px;" @click="dialogVisible = true">新增<i class="el-icon-plus el-icon--right"></i>
        </el-button>
        <!-- <el-row>
          <el-col :span="18">
             <el-input
              class="mt-1 mb-1"
              placeholder="请输入内容"
              prefix-icon="el-icon-search"
              clearable
              v-model="searchInput">
            </el-input>
          </el-col>
          <el-col :span="3"><el-button plain style="position:relative;top:3px" @click="getMainData(index,count)">查询</el-button></el-col>
        </el-row> -->
       
      </div>
      
      <div>
        <el-table
          ref="multipleTable"
          :data="realData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection">
          </el-table-column>

          <el-table-column
            label="新闻标题">
            <template slot-scope="scope">{{ scope.row.XWBT }}</template>
          </el-table-column>

          <el-table-column
            label="副标题">
            <template slot-scope="scope">{{ scope.row.XWFBT }}</template>
          </el-table-column>

          <!-- <el-table-column
            label="内容"
            width="220">
            <template slot-scope="scope">
              <div v-html="scope.row.XWNR"></div>
            </template>
          </el-table-column> -->

          <el-table-column
            label="封面图片">
            <template slot-scope="scope">
               <img v-if="scope.row.FMTP" :src="scope.row.FMTP" alt="" style="width: 36px;height:36px">
            </template>
          </el-table-column>

         
           <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
              <el-button v-if="userType=='0'" @click="dialogVisible_Edit = true;handleEdit(scope.row)" type="text" size="small">编辑</el-button>
              <el-button v-if="userType=='0'" @click="handledelete(scope.row)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="block mt-3">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage3"
            :page-size="count"
            layout="prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>

      </div>

      

    </el-card>

    <!-- 添加结盟商的弹出界面 -->
    <el-dialog
      title="新闻新增"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleClose">
       <div class="add">
      <el-form :label-position="labelPosition" label-width="100px" :model="formLabelAlign">
        <el-form-item label="新闻标题">
          <el-input  v-model="formLabelAlign.XWBT" placeholder="请输入新闻标题"></el-input>
        </el-form-item>

        <el-form-item label="新闻副标题">
          <el-input v-model="formLabelAlign.XWFBT" placeholder="请输入新闻副标题"></el-input>
        </el-form-item>

       

        <el-form-item label="上传封面图片">
          <el-row>
            <el-col :span="4">
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :http-request="savePicture"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-change = "onchange"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon imgBorder"></i>
              </el-upload>
            </el-col>
          </el-row> 
          
        </el-form-item>

        <el-form-item label="选择形式">
          <el-row style="position:relative;top:-20px">
            <el-col :span="8">
              <el-radio v-model="radio_add" label="1">使用富文本编辑器</el-radio>
              <el-radio v-model="radio_add" label="2">输入网址</el-radio>
            </el-col>
          </el-row>
        </el-form-item>


         <el-form-item label="新闻内容">
          <vue-editor v-if="radio_add=='1'" v-model="formLabelAlign.XWNR" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>
          <el-input   v-if="radio_add=='2'" v-model="formLabelAlign.XWNR" placeholder="请输入新闻网址"></el-input>
        </el-form-item>
          <!-- <el-button type="primary" @click="franchiseesAdd()">确 定</el-button> -->
      </el-form>
    </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false;handleCancle()">取 消</el-button>
        <el-button type="primary" @click="franchiseesAdd()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑的界面 -->
    <el-dialog
      title="新闻编辑"
      :visible.sync="dialogVisible_Edit"
      width="80%"
      :before-close="handleClose">
      <el-form :label-position="labelPosition" label-width="100px" :model="editData">
        <el-form-item label="新闻标题">
          <el-input  v-model="editData.XWBT" placeholder="请输入新闻标题"></el-input>
        </el-form-item>

        <el-form-item label="新闻副标题">
          <el-input v-model="editData.XWFBT" placeholder="请输入新闻副标题"></el-input>
        </el-form-item>

       

        <el-form-item label="上传封面图片">
          <el-row>
            <el-col :span="4">
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :http-request="savePicture"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-change = "onchange"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon imgBorder"></i>
              </el-upload>
            </el-col>
          </el-row> 
          
        </el-form-item>

        <el-form-item label="编辑形式">
          <el-row style="position:relative;top:-20px">
            <el-col :span="8">
              <el-radio v-model="radio_edit" label="1">使用富文本编辑器</el-radio>
              <el-radio v-model="radio_edit" label="2">输入网址</el-radio>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="新闻内容">
          <vue-editor v-if="radio_edit=='1'" v-model="editData.XWNR" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>
          <el-input   v-if="radio_edit=='2'" v-model="editData.XWNR" placeholder="请输入新闻网址"></el-input>
        </el-form-item>

          <!-- <el-button type="primary" @click="franchiseesAdd()">确 定</el-button> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_Edit = false">取 消</el-button>
        <el-button type="primary" @click="franchiseesEdit()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看的页面 -->
    <el-dialog
      title="详情"
      :visible.sync="dialogVisible_look"
      width="60%"
      :before-close="handleClose">
      <el-card class="box-card">
        <!-- <el-row>
          <el-col :span="8">新闻标题 :</el-col>
          <el-col :span="8">{{lookData.XWBT}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="8">新闻副标题 :</el-col>
          <el-col :span="8">{{lookData.XWFBT}}</el-col>
        </el-row> -->
          <div>
              <div v-html="lookData.XWNR"  class="imgContainner"></div>
          </div>
        <!-- <el-row>
          <el-col :span="8">封面图片 :</el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="4">
                 <img v-if="lookData.FMTP" :src="lookData.FMTP" width="100px" height="100px">
              </el-col>
            </el-row> 
          </el-col>
        </el-row> -->
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_look = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible_look = false">确 定</el-button>
      </span>
    </el-dialog>


 </div>
</template>


<script>
import { VueEditor } from "vue2-editor";
  export default {
    components: {
      VueEditor
    },
    data() {
      return {
        realData:[],
        multipleSelection: [],
        //添加界面弹出层参数 
        dialogVisible: false,
        //编辑界面弹出层参数
        dialogVisible_Edit:false,
        //查看界面弹出层参数
        dialogVisible_look:false,
        //添加新闻参数
        labelPosition: 'left',
        formLabelAlign: {
          XWBT: '',
          XWFBT: '',
          XWNR: '',
          FMTP:'',
        },
        //上传图片模块必须要定义的参数
        imageUrl:'',
        fileArr:[],
        uid:'',  // 存储在本地的uid
        editData:{
          OBJID:'', //uid 
          XWBT:'', // 新闻标题
          XWFBT:'', // 新闻副标题
          XWNR:'', //新闻内容  
          FMTP:'' //封面图片
        },
        lookData:{
          XWBT:'', // 新闻标题
          XWFBT:'', // 新闻副标题
          XWNR:'', //新闻内容  
          FMTP:'' //封面图片
        },
        searchInput:'',//查询
        currentPage3: 1,//当前页面，默认初始化为1
        total:100,    //分页总数
        index:0,  //自定义获取数据参数
        count:9,  // 分页长度（每页展示的数据数量）   
        radio_add:'1',
        radio_edit:'1'
      }
    },

    methods: {
      /* 富文本编辑器自定义图片(添加) */
      handleImageAdded: function(file, Editor, cursorLocation, resetUploader) {
        // An example of using FormData
        // NOTE: Your key could be different such as:
        // formData.append('file', file)
        console.log('富文本参数 ————————————————');
        console.log(file);
        console.log(Editor);
        console.log(cursorLocation);
        console.log(resetUploader);
        console.log('富文本参数 —————————end———————');

        this.uploadEditorImage(file, Editor, cursorLocation, resetUploader)

        /*官网逻辑
         var formData = new FormData();
        formData.append("image", file);
  
        axios({
          url: "https://fakeapi.yoursite.com/images",
          method: "POST",
          data: formData
        })
          .then(result => {
            let url = result.data.url; // Get url from response
            Editor.insertEmbed(cursorLocation, "image", url);
            resetUploader();
          })
          .catch(err => {
            console.log(err);
          }); */

      },
      /* 分页 */
      handleSizeChange(val) {
        // console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.getMainData((val-1)*this.count,this.count)
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 查看
      handleClick(row){
        console.log(row);
        this.lookData = row
        this.dialogVisible_look = true
      },
      //新闻信息编辑
      handleEdit(row){
        // console.log(row);
        if(row.ACTIONID=='1002_WEB'){
          this.radio_edit=='2'
        }
        this.editData = row
        this.imageUrl = this.editData.FMTP
        console.log(this.editData);
      },
      check(val){
        // console.log(val);
        var data = this.formLabelAlign
        if(val=='phone'){
          console.log(data.phone);
           if(data.phone==''||data.phone=='undefined'){
             $(".phoneTip").html("手机号不能为空")
           }else{
             $(".phoneTip").html("")
           }         
        }else if(val=='password'){
          console.log(data.password);
           if(data.password==''||data.password=='undefined'){
             $(".passwordTip").html("密码不能为空")
           }else{
             $(".passwordTip").html("")
           }         
        }else if(val=='username'){
          console.log(data.username);
           if(data.username==''||data.username=='undefined'){
               $(".usernameTip").html("名称不能为空")
           }else{
             var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》+-/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]");
          　　if (pattern.test(data.username)){
                 console.log('1');
                 $(".usernameTip").html("名称不能含有特殊字符")
          　　　　return true;
          　　}
              console.log('2');
              $(".usernameTip").html("")
           }         
        }else if(val=='indroduce'){
          console.log(data.indroduce);
           if(data.indroduce==''||data.indroduce=='undefined'){
             $(".indroduceTip").html("介绍不能为空")
           }else{
             $(".indroduceTip").html("")
           }         
        }else if(val=='address'){
          console.log(data.address);
           if(data.address==''||data.address=='undefined'){
             $(".addressTip").html("地址不能为空")
           }else{
             $(".addressTip").html("")
           }         
        }

      },
      check2(val){
        // console.log(val);
        var data = this.editData
        if(val=='SJHM'){
          console.log(data.SJHM);
           if(data.SJHM==''||data.SJHM=='undefined'){
             $(".SJHMTip").html("手机号不能为空")
           }else{
             $(".SJHMTip").html("")
           }         
        }else if(val=='XSMC'){
          console.log(data.XSMC);
           if(data.XSMC==''||data.XSMC=='undefined'){
               $(".XSMCTip").html("名称不能为空")
           }else{
             var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》+-/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]");
          　　if (pattern.test(data.XSMC)){
                 console.log('1');
                 $(".XSMCTip").html("名称不能含有特殊字符")
          　　　　return true;
          　　}
              console.log('2');
              $(".XSMCTip").html("")
           }         
        }

      },
      //input获取焦点隐藏错误提示
      hideTip(val){
        if(val=='phone'){
          $('.phoneTip').html('')
        }else if(val=='username'){
          $('.usernameTip').html('')
        }else if(val=='SJHM'){
          $('.SJHMTip').html('')
        }else if(val=='XSMC'){
          $('.XSMCTip').html('')
        }
      },


      /* 新闻新增 */
      async franchiseesAdd(row){

        var data = this.formLabelAlign

        if(data.XWBT==''){
          this.$message({
            message: '标题不能为空',
            type: 'warning',
            duration:1000
          });
          return
        }

        if(data.XWFBT==''){
          this.$message({
            message: '副标题不能为空',
            type: 'warning',
            duration:1000
          });
          return
        }

        if(data.XWNR==''){
          this.$message({
            message: '内容不能为空',
            type: 'warning',
            duration:1000
          });
          return
        }

        if(this.imageUrl==''){
          this.$message({
            message: '图片不能为空',
            type: 'warning',
            duration:1000
          });
          return
        }


        // if(this.fileArr.length>0){
          this.upload(this.fileArr[this.fileArr.length-1])
        // }
      },
      //添加结盟商成功后 或 取消添加时  =>  清空form数据 
      clearFormAddData(){
        var that = this
        that.formLabelAlign.XWBT=''
        that.formLabelAlign.XWFBT=''
        that.formLabelAlign.XWNR=''
        that.imageUrl=''
      },

      /* 结盟商编辑 */
      franchiseesEdit(){
        var data = this.editData
        console.log(data);

        if(data.XWBT==''){
          this.$message({
            message: '标题不能为空',
            type: 'warning',
            duration:1000
          });
          return
        }

        if(data.XWFBT==''){
          this.$message({
            message: '副标题不能为空',
            type: 'warning',
            duration:1000
          });
          return
        }

        if(data.XWNR==''){
          this.$message({
            message: '内容不能为空',
            type: 'warning',
            duration:1000
          });
          return
        }

        if(this.imageUrl==''){
          this.$message({
            message: '图片不能为空',
            type: 'warning',
            duration:1000
          });
          return
        }

        if(this.fileArr.length>0){
          this.upload2(this.fileArr[this.fileArr.length-1])
        }else{ 
              var that = this
               var data =  that.editData

                var params = {}
                params.ACTIONNAME = 'saveXWDT';

                if(that.radio_edit=='2'){
                   params.ACTIONID = '1002_WEB';
                }

                params.uid = that.uid;
                params.objid = data.OBJID;
                params.XWBT = data.XWBT;
                params.XWFBT = data.XWFBT;
                params.XWNR = data.XWNR;
                params.PX = 0;

                that.$get(params).then(res => {
                  console.log(res)
                  if(res.SUCCESS){
                     that.$message({
                      message: res.MSG,
                      type: 'success',
                      duration:1000
                    });
                     that.getMainData(that.index,that.count)
                     that.dialogVisible_Edit = false
                  }else{
                    that.$message({
                      message: res.MSG,
                      type: 'warning',
                      duration:1000
                    });
                    that.dialogVisible_Edit = false
                  }
                })

        }
      },

      /* 弹出层关闭前  （X号关闭）*/
      handleClose(done) {
        done();
        this.clearFormAddData()
      },
      handleCancle(){
       this.clearFormAddData()
      },
      /* 上传头像 */
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      onchange(file){
        // console.log(file);      
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return
        }
         this.handleAvatarSuccess(file,file)
      },
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isJPG = true;
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      /*自定义存储图片，点击上传后调用 upload(param) 上传 */
      savePicture(req){
        this.fileArr.push(req.file)
      },

      /* 上传图片自定义事件 */
      upload(file){
        var that = this    

        var file = file; // 对象，上传的文件
        var fileExtension = (file.name).split('.').pop();
        var key = this.$md5(file.name)+"."+fileExtension; // 文件资源名
        /*
        * config.useCdnDomain: 是否使用 cdn 加速域名，true or false，默认为 false。
        * config.disableStatisticsReport: 是否禁用日志报告，为布尔值，默认为false。
        * config.region: 选择上传域名区域；当为 null 或 undefined 时，自动分析上传域名区域
        * config.retryCount: 上传自动重试次数（整体重试次数）；默认3次（即上传失败后最多重试两次）；
        * config.concurrentRequestLimit: 分片上传的并发请求量，number，默认为3；
        * config.checkByMD5: 是否开启 MD5 校验，在断点续传时校验分片，默认为 false，不开启。
        */
        let config = {
            useCdnDomain: true, 
            region: this.$qiniu.region.z0
        };

        /*
        * fname: string，文件原文件名.
        * params: object，用来放置自定义变量;
        * mimeType: null || array，用来限制上传文件类型，为 null 时表示不对文件类型限制；
        * 限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
        */
        let putExtra = {
            fname: file,
            params: {}, 
            mimeType: ["image/png", "image/jpeg", "image/gif"]
        };
        let observe = {
            next (res) {
                console.log('已上传大小，单位为字节：' + res.total.loaded)
                console.log('本次上传的总量控制信息，单位为字节：' + res.total.size)
                console.log('当前上传进度，范围：0～100：' + res.total.percent);
            },
          error (err) {
                console.log(err.code)
                console.log(err.message)
                console.log(err.isRequestError)
                console.log(err.reqId)
            },
            complete (res) {
                //完成后的操作
                //上传成功以后会返回key 和 hash  key就是文件名了！
                console.log(res)
                console.log('http://img.lingdongzhe.com/'+res.key);
                
                 console.log(that.formLabelAlign);
                var data =  that.formLabelAlign

                var params = {}
                params.ACTIONNAME = 'saveXWDT';

                if(that.radio_add=='2'){
                   params.ACTIONID = '1002_WEB';
                }

                params.uid = that.uid;
                params.XWBT = data.XWBT;
                params.XWFBT = data.XWFBT;
                params.XWNR = data.XWNR;
                params.PX = 0;
                params.FMTP = 'http://img.lingdongzhe.com/'+res.key

                that.$get(params).then(res => {
                  console.log(res)
                  if(res.SUCCESS){
                     that.$message({
                      message: res.MSG,
                      type: 'success',
                      duration:1000
                    });
                    that.getMainData(that.index,that.count)
                    that.clearFormAddData()
                    that.dialogVisible = false
                  }else{
                    console.log('错误');
                    that.$message({
                      message: res.MSG,
                      type: 'warning',
                      duration:1000
                    });
                  }
                })

            }
        };

        var params2 = {}
        params2.ACTIONNAME = 'getQiniutoken'
        params2.uid = that.uid;
        this.$get(params2).then(res => {
          var upToken =  res.DATA
          console.log('upToken : '+upToken);
          //开始上传  token 需要找后端获取(单独的方法)
          let observable = this.$qiniu.upload(file, key, upToken, putExtra, config)
          let subscription = observable.subscribe(observe)
        })
        
        // //开始上传  token 需要找后端获取(单独的方法)
        // let observable = this.$qiniu.upload(file, key, upToken, putExtra, config)
        // let subscription = observable.subscribe(observe)
      },

       /* 编辑 上传图片自定义事件 */
      upload2(file){
        var that = this    
        var file = file; // 对象，上传的文件
        var fileExtension = (file.name).split('.').pop();
        var key = this.$md5(file.name)+"."+fileExtension; // 文件资源名
        let config = {
            useCdnDomain: true, 
            region: this.$qiniu.region.z0
        };
        let putExtra = {
            fname: file,
            params: {}, 
            mimeType: ["image/png", "image/jpeg", "image/gif"]
        };
        let observe = {
            next (res) {
                console.log('已上传大小，单位为字节：' + res.total.loaded)
                console.log('本次上传的总量控制信息，单位为字节：' + res.total.size)
                console.log('当前上传进度，范围：0～100：' + res.total.percent);
            },
          error (err) {
                console.log(err.code)
                console.log(err.message)
                console.log(err.isRequestError)
                console.log(err.reqId)
            },
            complete (res) {
                //完成后的操作
                //上传成功以后会返回key 和 hash  key就是文件名了！
                console.log(res)
                console.log('http://img.lingdongzhe.com/'+res.key);
                
                var data =  that.editData

                var params = {}
                params.ACTIONNAME = 'saveXWDT';

                if(that.radio_edit=='2'){
                   params.ACTIONID = '1002_WEB';
                }

                params.uid = that.uid;
                params.objid = data.OBJID;
                params.XWBT = data.XWBT;
                params.XWFBT = data.XWFBT;
                params.XWNR = data.XWNR;
                params.PX = 0;
                params.FMTP = 'http://img.lingdongzhe.com/'+res.key

                that.$get(params).then(res => {
                  console.log(res)
                  if(res.SUCCESS){
                     that.$message({
                      message: res.MSG,
                      type: 'success',
                      duration:1000
                    });
                     that.getMainData(that.index,that.count)
                     that.dialogVisible_Edit = false
                  }else{
                    that.$message({
                      message: res.MSG,
                      type: 'warning',
                      duration:1000
                    });
                    that.dialogVisible_Edit = false
                  }
                })

            }
        };

        var params2 = {}
        params2.ACTIONNAME = 'getQiniutoken'
        params2.uid = that.uid;
        this.$get(params2).then(res => {
          var upToken =  res.DATA
          console.log('upToken : '+upToken);
          //开始上传  token 需要找后端获取(单独的方法)
          let observable = this.$qiniu.upload(file, key, upToken, putExtra, config)
          let subscription = observable.subscribe(observe)
        })
        
        // //开始上传  token 需要找后端获取(单独的方法)
        // let observable = this.$qiniu.upload(file, key, upToken, putExtra, config)
        // let subscription = observable.subscribe(observe)
      },

       /* 富文本自定义上传图片 */
      uploadEditorImage(file, Editor, cursorLocation, resetUploader){
        var that = this    
        var file = file; // 对象，上传的文件
        var fileExtension = (file.name).split('.').pop();
        var key = this.$md5(file.name)+"."+fileExtension; // 文件资源名
        let config = {
            useCdnDomain: true, 
            region: this.$qiniu.region.z0
        };
        let putExtra = {
            fname: file,
            params: {}, 
            mimeType: ["image/png", "image/jpeg", "image/gif"]
        };
        let observe = {
            next (res) {
                console.log('已上传大小，单位为字节：' + res.total.loaded)
                console.log('本次上传的总量控制信息，单位为字节：' + res.total.size)
                console.log('当前上传进度，范围：0～100：' + res.total.percent);
            },
          error (err) {
                console.log(err.code)
                console.log(err.message)
                console.log(err.isRequestError)
                console.log(err.reqId)
            },
            complete (res) {
                //完成后的操作
                //上传成功以后会返回key 和 hash  key就是文件名了！
                console.log(res)
                console.log('http://img.lingdongzhe.com/'+res.key);
                
                let url = 'http://img.lingdongzhe.com/'+res.key; // Get url from response
                Editor.insertEmbed(cursorLocation, "image", url);
                resetUploader();
                
            }
        };

        var params2 = {}
        params2.ACTIONNAME = 'getQiniutoken'
        params2.uid = that.uid;
        this.$get(params2).then(res => {
          var upToken =  res.DATA
          console.log('upToken : '+upToken);
          //开始上传  token 需要找后端获取(单独的方法)
          let observable = this.$qiniu.upload(file, key, upToken, putExtra, config)
          let subscription = observable.subscribe(observe)
        })
        
        // //开始上传  token 需要找后端获取(单独的方法)
        // let observable = this.$qiniu.upload(file, key, upToken, putExtra, config)
        // let subscription = observable.subscribe(observe)
      },

      handledelete(row){
        var that = this
        console.log(row);
        that.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var params = {}
          params.ACTIONNAME = 'delNewOrBanner';

          console.log(localStorage.token);
          console.log(row.OBJID);
          
          params.uid = localStorage.token;
          params.objid = row.OBJID;
          
          this.$get(params).then(res => {
            if(res.SUCCESS){
                that.$message({
                message: res.MSG,
                type: 'success',
                duration:1000
              });
                that.getMainData(that.index,that.count)
            }else{
              that.$message({
                message: res.MSG,
                type: 'warning',
                duration:1000
              });
            }
          })
        })
        
      },
      /* 获取上传七牛云token，与本身token无关 */
      getToken(){
        var params2 = {}
        params2.ACTIONNAME = 'getQiniutoken';
        params2.uid = '0';
        this.$get(params2).then(res => {
          this.upToken =  res.DATA
        })
      },
      /* 获取主数据，第一次进入页面加载的数据 */
      async getMainData(index,count){
        
        var params = {}
        params.ACTIONNAME = 'getNewsList1';
        params.index = index;
        params.count = count;
        if(this.searchInput!==''){
          params.keywords = this.searchInput;
        }
        this.$get(params).then(res => {
          // window.console.log(res)
          console.log(res)
          this.realData = res.DATA.LIST
          this.total = res.DATA.TOTAL;
        })
      },
    },
    created(){
      this.userType = localStorage.userType
      this.uid = localStorage.uid
      this.getMainData(this.index,this.count)
    }
  }
</script>

<style scoped>
 .text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.el-table{
  width: 600px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
/* 头像 */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader-icon[data-v-3f78ccf2] {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px solid #DCDFE6;
}

.el-form-item{
  position: relative;
}
.tip{
    color: #9d0b0b;
    position: absolute;
    right: 1%;
    top: 0;
}

.el-row {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 20px 0;
}

.el-table .cell {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    white-space: normal;
    word-break: break-all;
    line-height: 23px;
    white-space: nowrap;

    overflow: hidden !important;
    text-overflow: ellipsis;
}
</style>